import dayjs from "dayjs";
// 节流函数
export const throttle = (cb, wait) => {
  // 节流
  let preTime = 0; //标识
  return function () {
    let context = this;
    let args = arguments;
    let now = +new Date();
    if (now - preTime > wait) {
      cb.apply(context, args);
      preTime = now;
    }
  };
};

// 防抖函数
export const debounce = (fn, time, flag) => {
  let timer = null;
  return function (...args) {
    clearTimeout(timer);
    if (flag && !timer) {
      fn.apply(this, args);
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, time);
  };
};

// 计算价格 保留两位小数展示
export const computedPrice = (num) => {
  return Math.round(num * 100) / 100;
};

// uniapp刷新当前页面
export const reload = () => {
  let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
  let curRoute = routes[routes.length - 1].route; // 获取当前页面路由，也就是最后一个打开的页面路由
  uni.reLaunch({
    url: "/" + curRoute,
  });
};

// 获取是否路由有 有的话返回
export const toCurrentPage = (path) => {
  let routes = getCurrentPages().map((item) => "/" + item.route); // 获取当前打开过的页面路由数组
  const index = routes.indexOf(path);
  if (index > -1) {
    uni.navigateBack({
      delta: routes.length - index - 1,
    });
  } else {
    uni.navigateTo({
      url: path,
    });
  }
};

// 延迟函数
export const delay = (ms) =>
  new Promise((resolve, reject) => setTimeout(resolve, ms));

// 播放音频
export const playMp3 = (url, count = 1) => {
  // 设置静音也不播放
  // const configStore = useConfigStore();
  // if (configStore.getIsMute != 1) {
  //   return;
  // }
  // 递归终止条件，循环次数小于0
  if (count <= 0) return;
  // 音频播放
  const innerAudioContext = uni.createInnerAudioContext();
  innerAudioContext.autoplay = true;
  innerAudioContext.src = url;
  innerAudioContext.onPlay(() => {
    console.log("开始播放");
  });
  innerAudioContext.onError((res) => {
    console.log(res.errMsg);
    console.log(res.errCode);
  });
  innerAudioContext.onEnded(() => {
    // 销毁音频上下文对象，以释放资源
    innerAudioContext.destroy();
    // 在音频播放结束后，延迟一定时间重新调用函数循环播放
    setTimeout(() => {
      playMp3(url, count - 1);
    }, 1000);
  });
};

// 计算购物车商品价格
export const getGoodsTotalPrice = (goodsList) => {
  try {
    let total = 0;
    if (!Array.isArray(goodsList)) {
      return;
    }
    goodsList.forEach((item) => {
      if (!item.specs_price) {
        item.specs_price = 0;
      }
      total += (+item.price + +item.specs_price) * item.number;
      if (item.dishes_price) {
        total += item.dishes_price * item.number;
      }
    });
    return computedPrice(total);
  } catch (e) {
    console.log(e);
  }
};
// 计算时间差值（分钟）
export const diffMin = (time1 = null, time2 = null) => {
  // 假设有两个时间字符串
  // const time1 = "2023-04-01 12:00:00";
  // const time2 = "2023-04-02 15:30:00";

  // 使用Day.js解析时间字符串
  const date1 = dayjs(time1);
  const date2 = time2 ? dayjs(time2) : dayjs();
  // 计算时间差
  const duration = date2.diff(date1); // 返回的是毫秒数

  // 转换为其他单位，例如分钟
  const diffInMinutes = Math.floor(duration / 1000 / 60); // 将毫秒转换为分钟
  return diffInMinutes;
};


/**
 * // 比较时间是否超过了多少分钟
 * @param {*} date 比较的日期
 * @param {*} diff 分钟数 毫秒 默认10分钟
 * @returns 
 */
export function getIsDiffMinute(date, diff=10*60*1000) {
  const now = Date.now();
  const str = new Date(date).getTime()
  if (now - str > diff) {
    return true
  } else {
    return false
  }
}
